
// 监听扩展安装或更新事件
chrome.runtime.onInstalled.addListener(() => {
  console.log('扩展已安装或更新');
  // 确保先移除已存在的菜单项，防止重复
  chrome.contextMenus.removeAll(() => {
    // 创建新的菜单项
    chrome.contextMenus.create({
      id: 'immersiveMemory',
      title: '沉浸式记忆',
      contexts: ['selection']
    }, () => {
      if (chrome.runtime.lastError) {
        console.error('创建菜单失败:', chrome.runtime.lastError);
      }
    });
    
    // 添加辅助理解菜单项
    chrome.contextMenus.create({
      id: 'assistantUnderstanding',
      title: '辅助理解',
      contexts: ['selection']
    }, () => {
      if (chrome.runtime.lastError) {
        console.error('创建菜单失败:', chrome.runtime.lastError);
      }
    });
  });
});

// 添加服务工作进程激活事件监听
chrome.runtime.onStartup.addListener(() => {
  console.log('插件浏览器启动，服务工作进程已激活');
});

// 保持服务工作进程活跃
self.addEventListener('activate', event => {
  event.waitUntil(clients.claim());
  console.log('Service Worker 已激活');
});

// 添加调试日志
console.log('Background script 已加载');

// 处理菜单点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'immersiveMemory') {
    chrome.tabs.sendMessage(tab.id, {
      action: 'showSidebar'
    });
  } else if (info.menuItemId === 'assistantUnderstanding') {
    chrome.tabs.sendMessage(tab.id, {
      action: 'showAssistantSidebar'
    });
  }
});

// 处理API请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'callLLMAPI') {
    const { url, options } = request;
    
    fetch(url, options)
      .then(response => response.json())
      .then(data => sendResponse({ success: true, data }))
      .catch(error => sendResponse({ success: false, error: error.message }));
      
    return true; // 保持消息通道打开以等待异步响应
  }
}); 